package org.dxy.domain.model.aggregate.factory.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.port.repository.IProductionLineRepository;
import org.dxy.domain.port.repository.IRouteRepository;
import org.dxy.domain.command.workorder.CreateWorkOrderCommand;
import org.dxy.domain.model.aggregate.factory.WorkOrderFactory;
import org.dxy.domain.model.aggregate.WorkOrder;
import org.springframework.stereotype.Component;

/**
 * 工单工厂实现类
 * @author dxy
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class WorkOrderFactoryImpl implements WorkOrderFactory {
    
    private final IRouteRepository routeRepository;
    private final IProductionLineRepository productionLineRepository;
    
    @Override
    public WorkOrder create(Long workOrderId, CreateWorkOrderCommand command) {
        log.info("开始创建工单聚合根, workOrderId={}, command={}", workOrderId, command);
        
        // 1. 业务规则验证
        validateBusinessRules(command);
        
        // 2. 创建工单聚合根
        WorkOrder workOrder = WorkOrder.create(workOrderId, command);
        
        log.info("工单聚合根创建成功, workOrderId={}", workOrderId);
        return workOrder;
    }
    
    /**
     * 验证业务规则
     * @param command 创建工单命令
     */
    private void validateBusinessRules(CreateWorkOrderCommand command) {
        // 1. 校验工艺路线是否存在（如果指定了）
        if (command.routeId() != null && !routeRepository.existsById(command.routeId())) {
            throw new IllegalArgumentException("工艺路线不存在: " + command.routeId());
        }
        
        // 2. 校验产线是否存在且可用（如果指定了）
        if (command.productionLineId() != null) {
            if (!productionLineRepository.existsById(command.productionLineId())) {
                throw new IllegalArgumentException("产线不存在: " + command.productionLineId());
            }
            if (!productionLineRepository.isAvailable(command.productionLineId())) {
                throw new IllegalArgumentException("产线不可用（可能在维护中）: " + command.productionLineId());
            }
        }
        
        log.debug("工单业务规则验证通过, command={}", command);
    }

}